package com.health.controller;

import com.aliyuncs.exceptions.ClientException;
import com.health.constant.MessageConstant;
import com.health.constant.RedisMessageConstant;
import com.health.entity.Result;
import com.health.pojo.Order;
import com.health.service.OrderService;
import com.health.utils.SMSUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private OrderService orderService;

    @PostMapping("/submit.do")
    public Result submit(@RequestBody Map map){
        String telephone=(String) map.get("telephone");
        String validateCodeInRedis= (String) redisTemplate.opsForValue().get(telephone+ RedisMessageConstant.SENDTYPE_ORDER);
        String validate=(String) map.get("validateCode");
        if(validateCodeInRedis!=null&&validate!=null&&validate.equals(validateCodeInRedis)){
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result=null;
            try {
                result= orderService.order(map);
            }catch (Exception e){
                e.printStackTrace();
                return result;
            }
            if(result.isFlag()){
                try {
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,(String) map.get("orderDate"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return result;
        }else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    @PostMapping("/findById.do")
    public Result findById(Integer id){
        try{
            Map map=orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
